package com.sun;

import java.util.HashMap;

/**
 *https://leetcode.cn/problems/roman-to-integer/
 */
public class Test13罗马数字转为整数 {
    public static void main(String[] args) {
        int res = romanToInt2("III");
        System.out.println(res);
    }

    /**
     *方法1：自己
     */
    public static int romanToInt1(String s){
        HashMap<String,Integer> map = new HashMap<>(){
            {
                put("I",1);put("IV",4);put("V",5);put("IX",9);put("X",10);put("XL",40);put("L",50);
                put("XC",90);put("C",100);put("CD",400);put("D",500);put("CM",900);put("M",1000);
            }
        };
        int res = 0;
        String str;
        for (int i = 0; i < s.length();) {
            str = s.substring(i,i+2 <= s.length() ? i + 2 : i + 1);
            if (map.containsKey(str)){
                res += map.get(str);
                i += 2;
            }else {
                str = s.substring(i,i + 1);
                res += map.get(str);
                i++;
            }
        }
        return res;
    }
    /**
     * 方法2：力扣官方模拟
     */
    public static int romanToInt2(String s){
        int res = 0;
        HashMap<Character,Integer> map = new HashMap<>(){{
            put('I', 1);
            put('V', 5);
            put('X', 10);
            put('L', 50);
            put('C', 100);
            put('D', 500);
            put('M', 1000);
        }};
        for (int i = 0; i < s.length(); i++) {
            int value = map.get(s.charAt(i));
            if (i < s.length() - 1 && value < map.get(s.charAt(i + 1))){
                res -= value;
            }else {
                res += value;
            }
        }
        return res;
    }

}
